<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型" prop="proType">
              <el-select v-model="queryParams.proType" placeholder="请选择项目类型" clearable>
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态" prop="proStatus">
              <el-select v-model="queryParams.proStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in project_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['project:receive:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="statisticList" border>
        <el-table-column label="子项目名称" align="center" prop="proName" min-width="150" show-overflow-tooltip />
        <el-table-column label="子项目编号" align="center" prop="proNumber" min-width="150" />
        <el-table-column label="项目执行总裁" align="center" prop="proPresidentsName" min-width="150" show-overflow-tooltip />
        <el-table-column label="项目负责人" align="center" prop="proLeadersName" min-width="150" show-overflow-tooltip />
        <el-table-column label="收款负责人" align="center" prop="receiveLeadersName" min-width="150" show-overflow-tooltip />
        <el-table-column
          label="本项目已达节点总金额
"
          align="center"
          prop="totalAmount"
          min-width="150"
        >
          <template #default="scope">
            <span class="amount-text total-amount">{{ formatAmount(scope.row.totalAmount) }}元</span>
          </template>
        </el-table-column>
        <el-table-column
          label="本项目已回款总金额
"
          align="center"
          prop="receivedAmount"
          min-width="150"
        >
          <template #default="scope">
            <span class="amount-text received-amount">{{ formatAmount(scope.row.receivedAmount) }}元</span>
          </template>
        </el-table-column>
        <el-table-column
          label="本项目剩余应收款金额
"
          align="center"
          prop="surplusAmount"
          min-width="150"
        >
          <template #default="scope">
            <span class="amount-text surplus-amount">{{ formatAmount(scope.row.surplusAmount) }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="回款完成率" align="center" min-width="150">
          <template #default="scope">
            <el-progress
              :percentage="calculateCompletionRate(scope.row)"
              :color="getProgressColor(scope.row)"
              :stroke-width="8"
              :show-text="true"
              :format="(percentage) => percentage.toFixed(1) + '%'"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link @click="handleViewDetail(scope.row)">
              <el-icon><View /></el-icon>
              <span>查看详情</span>
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无回款统计数据" />
        </template>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="ProReceiveStatistic" lang="ts">
import { ref, onMounted, getCurrentInstance, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { receiveStatistic } from '@/api/project/init/proInfo';
import type { ProInfoQuery, ProReceiveStatisticVo } from '@/api/project/init/proInfo/types';
import { View } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const router = useRouter();
const { project_type, project_status } = toRefs<any>(proxy?.useDict('project_type', 'project_status'));

const loading = ref(false);
const showSearch = ref(true);
const statisticList = ref<ProReceiveStatisticVo[]>([]);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<ProInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  proName: undefined,
  proType: undefined,
  proStatus: undefined,
  params: {}
});

/**
 * 格式化金额
 */
const formatAmount = (amount: number | string) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

/**
 * 计算回款完成率
 */
const calculateCompletionRate = (row: ProReceiveStatisticVo) => {
  const totalAmount = Number(row.totalAmount) || 0;
  const receivedAmount = Number(row.receivedAmount) || 0;

  if (totalAmount === 0) return 0;

  const rate = (receivedAmount / totalAmount) * 100;
  return Math.min(rate, 100); // 确保不超过100%
};

/**
 * 获取进度条颜色
 */
const getProgressColor = (row: ProReceiveStatisticVo) => {
  const rate = calculateCompletionRate(row);

  if (rate >= 80) return '#67C23A'; // 绿色 - 完成率很高
  if (rate >= 50) return '#E6A23C'; // 橙色 - 完成率中等
  if (rate >= 20) return '#F56C6C'; // 红色 - 完成率较低
  return '#909399'; // 灰色 - 完成率很低
};

/**
 * 查看详情
 */
const handleViewDetail = (row: ProReceiveStatisticVo) => {
  if (row.proId) {
    router.push(`/project/receive-edit/index/${row.proId}`);
  } else {
    ElMessage.warning('项目ID不存在无法查看详情');
  }
};

/**
 * 获取统计数据列表
 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bCreateTime: dateRange.value[0]?.toString(),
        eCreateTime: dateRange.value[1]?.toString()
      };
    }
    const res = await receiveStatistic(params);
    statisticList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取回款统计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bCreateTime: undefined,
    eCreateTime: undefined
  };
  handleQuery();
};

/**
 * 导出按钮操作
 */
const handleExport = () => {
  proxy?.download(
    'pro/info/receive/statistic/export',
    {
      ...queryParams.value
    },
    `pro_receive_statistic_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.amount-text {
  font-weight: bold;
  font-size: 14px;
}

.total-amount {
  color: #1f2937;
}

.received-amount {
  color: #10b981;
}

.surplus-amount {
  color: #f59e0b;
}

:deep(.el-progress) {
  .el-progress__text {
    font-size: 12px;
    font-weight: bold;
  }
}

:deep(.el-table) {
  .el-table__cell {
    vertical-align: middle;
  }
}
</style>
